<template>
  <view class="review-container">
    <view class="goods-list">
      <view v-for="item in orderItems" :key="item.id" class="goods-item">
        <image class="goods-image" :src="item.productImg" mode="aspectFill"></image>
        <view class="goods-info">
          <text class="goods-name">{{ item.productName }}</text>
          <text class="goods-spec" v-if="item.specInfo">{{ formatSpecInfo(item.specInfo) }}</text>
        </view>
      </view>
    </view>

    <view class="review-form">
      <view class="rating-section">
        <text class="section-title">商品评分</text>
        <uni-rate v-model="rating" size="25" active-color="#ff5500"></uni-rate>
      </view>

      <view class="content-section">
        <textarea 
          v-model="content" 
          class="review-content" 
          placeholder="请输入您的评价内容，对他人帮助很大哦~" 
          maxlength="500"
        ></textarea>
        <text class="word-count">{{ content.length }}/500</text>
      </view>

      <view class="image-section">
        <view class="section-title">上传图片</view>
        <view class="image-list">
          <view 
            v-for="(image, index) in images" 
            :key="index" 
            class="image-item"
          >
            <image :src="image" mode="aspectFill"></image>
            <text class="delete-btn" @tap="deleteImage(index)">×</text>
          </view>
          <view 
            class="upload-btn" 
            @tap="chooseImage" 
            v-if="images.length < 6"
          >
            <text class="iconfont icon-add"></text>
          </view>
        </view>
        <text class="tip-text">最多上传6张图片</text>
      </view>

      <view class="anonymous-section">
        <text>匿名评价</text>
        <switch 
          :checked="isAnonymous" 
          @change="(e) => isAnonymous = e.detail.value"
          color="#ff5500"
        />
      </view>
    </view>

    <view class="submit-btn" @tap="submitReview">提交评价</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderItems: [],
      rating: 5,
      content: '',
      images: [],
      isAnonymous: false,
      loading: false
    }
  },

  onLoad(options) {
    if (options.orderId) {
      this.orderId = options.orderId
      this.loadOrderDetail()
    }
  },

  methods: {
    // 加载订单详情
    async loadOrderDetail() {
      try {
        const res = await this.$api.orders.detail(this.orderId)
        console.log('订单详情:', res.data)
        if (res.data && res.data.orderItems) {
          this.orderItems = res.data.orderItems || []
        }
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    // 格式化规格信息
    formatSpecInfo(specInfo) {
      if (!specInfo) return '';
      try {
        const specs = JSON.parse(specInfo);
        return Object.values(specs).join(' ');
      } catch (e) {
        return specInfo;
      }
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 6 - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths)
        }
      })
    },

    // 上传图片
    async uploadImages(tempFilePaths) {
      uni.showLoading({ 
        title: '上传中...',
        mask: true
      })

      try {
        for (const tempFilePath of tempFilePaths) {
          try {
            // 检查token
            const token = uni.getStorageSync('token')
            if (!token) {
              throw new Error('未登录或token已过期')
            }

            // 使用社区模块的上传接口，因为评论模块的上传接口有问题
            const uploadRes = await this.$api.community.posts.uploadImage(tempFilePath)
            console.log('Upload Response:', uploadRes)
            
            // 直接使用返回的URL
            if (uploadRes) {
              this.images.push(uploadRes)
              console.log('添加图片URL到列表:', uploadRes)
            } else {
              throw new Error('上传失败，未获取到图片URL')
            }
            
          } catch (error) {
            console.error('上传图片失败:', error)
            uni.showToast({
              title: error.message || '图片上传失败',
              icon: 'none'
            })
            break // 如果上传失败，停止后续上传
          }
        }
      } catch (error) {
        console.error('选择图片失败:', error)
        uni.showToast({
          title: error.message || '选择图片失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 删除图片
    deleteImage(index) {
      this.images.splice(index, 1)
    },

    // 提交评价
    async submitReview() {
      if (this.loading) return
      if (!this.content.trim()) {
        uni.showToast({
          title: '请输入评价内容',
          icon: 'none'
        })
        return
      }

      try {
        this.loading = true
        
        // 获取当前订单的第一个商品信息
        const firstOrderItem = this.orderItems[0]
        console.log('商品信息:', firstOrderItem)
        
        if (!firstOrderItem) {
          throw new Error('未找到商品信息')
        }

        const productId = firstOrderItem.productId
        console.log('商品ID:', productId)
        
        if (!productId) {
          throw new Error('商品ID不能为空')
        }

        const params = {
          orderId: this.orderId,
          productId: productId,
          content: this.content.trim(),
          rating: this.rating,
          images: this.images,
          isAnonymous: this.isAnonymous
        }
        
        console.log('提交评价参数:', params)

        const result = await this.$api.user.comment.add(params)
        console.log('评价结果:', result)

        uni.showToast({
          title: '评价成功',
          icon: 'success'
        })

        // 延迟返回，让用户看到成功提示
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('评价失败:', error)
        uni.showToast({
          title: error.message || '评价失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.review-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.goods-list {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .goods-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;

    .goods-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
    }

    .goods-info {
      flex: 1;
      margin-left: 20rpx;

      .goods-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .goods-spec {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.review-form {
  background-color: #fff;
  padding: 30rpx;

  .section-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .rating-section {
    margin-bottom: 30rpx;
  }

  .content-section {
    position: relative;
    margin-bottom: 30rpx;

    .review-content {
      width: 100%;
      height: 240rpx;
      padding: 20rpx;
      box-sizing: border-box;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      font-size: 28rpx;
    }

    .word-count {
      position: absolute;
      right: 20rpx;
      bottom: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  .image-section {
    margin-bottom: 30rpx;

    .image-list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10rpx;

      .image-item, .upload-btn {
        width: 160rpx;
        height: 160rpx;
        margin: 10rpx;
        position: relative;
      }

      .image-item {
        image {
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }

        .delete-btn {
          position: absolute;
          top: -20rpx;
          right: -20rpx;
          width: 40rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          border-radius: 50%;
          font-size: 32rpx;
        }
      }

      .upload-btn {
        border: 1rpx dashed #ddd;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;

        .icon-add {
          font-size: 48rpx;
        }
      }
    }

    .tip-text {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }

  .anonymous-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #333;
  }
}

.submit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  background-color: #ff5500;
  color: #fff;
  font-size: 32rpx;
}
</style> 